package com.hp.bon.sgw.wh.mml;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.wh.mml.common.AckEntity;
import com.hp.bon.sgw.wh.mml.common.MMLSessionEntity;
import com.hp.bon.sgw.wh.mml.helper.LogMsgHelper;
import com.hp.bon.sgw.wh.mml.repositories.HttpResponseRepository;
import com.hp.bon.sgw.wh.mml.repositories.VCMsgRelayRepository;
import com.hp.bon.sgw.wh.mml.repositories.VCMsgRepository;

import ch.unifr.nio.framework.transform.AbstractForwarder;

public class VCClientTransformer extends AbstractForwarder<String, Void> {

	private static final Logger logger = LoggerFactory.getLogger(VCClientTransformer.class);
	
	@Override
	public void forward(String vcResponse) throws IOException {
		// print out incoming string
		logger.info("VCClientTransformer forward recv: ====");
		logger.info(vcResponse);
		logger.info("============recv message end==========");
		LogMsgHelper.appendLogMsg(vcResponse);
		//校验消息 字节
		
		//检验是否是心条 消息
		String heartbeat = MMLDecoder.parseVCHearBeat(vcResponse);
		if(heartbeat!=null){
			logger.info("sgw will echo vc heartbeat: " + heartbeat);
			VCMsgRepository.offerVCHeartBeatMsg(heartbeat);
			return;
		}
		
		//提取SessionId
		String sessionId = MMLDecoder.parseSessionId(vcResponse);
		if(sessionId==null || !VCMsgRelayRepository.findSessionId(sessionId)){
			logger.error("Not Valid Session Id:" + sessionId);
			return;
		}
		//提取mmlCommand
		AckEntity ackEntity = MMLDecoder.parseMMLCommand(vcResponse);
		if(ackEntity==null){
			VCMsgRelayRepository.remove(sessionId);
			logger.error("No ACK Command of Session Id:" + sessionId);
			return;
		}
		//把VC ACK 信息加入到 MMLSessionEntity
		MMLSessionEntity sessionEntity = VCMsgRelayRepository.get(sessionId);
		if(sessionEntity==null){
			logger.error("VCMsgRelayRepository NOT contain Session Id:" + sessionId);			
			return;
		}
		sessionEntity.addAckEntity(ackEntity);
		
		//if login ACK
		if(ackEntity.getAckType().equals(AckEntity.TYPE_LOGIN)){
			String status = ackEntity.getAckItemValue(AckEntity.KEY_RETN);
			if(AckEntity.STATUS_OK.equals(status)){
				//if ACK success, send transaction package
				VCMsgRepository.offerVCMsg(sessionEntity);
			} else {
				//if ACK fail, don't send transaction package, only http response
				HttpResponseRepository.offer(sessionEntity);
				//remove the entity from VCMsgRelayRepository
				VCMsgRelayRepository.remove(sessionId);
			}
		}
		//if transaction ACK
		if(ackEntity.getAckType().equals(AckEntity.TYPE_TRANSACTION)){
			//不管transaction ACK是否正确，一定要做Logout
			VCMsgRepository.offerLogoutMsg(sessionEntity);
		}
		//if logout ACK
		if(ackEntity.getAckType().equals(AckEntity.TYPE_LOGOUT)){
			HttpResponseRepository.offer(sessionEntity);
			//remove the entity from VCMsgRelayRepository
			VCMsgRelayRepository.remove(sessionId);
		}
	}

}
